import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/delete")
public class DeleteBlog extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应的格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //1.从请求中获取session
        HttpSession session = req.getSession();
        if(session == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录，不可以删除博客!");
            return;
        }
        //2.从session中获取user对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录，不可以删除博客!");
            return;
        }
        //3.从请求中获取博客ID
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前博客ID异常");
            return;
        }
        //4.根据博客ID从数据库中取出相应博客
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
        if(blog == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前博客ID异常");
            return;
        }
        //5.拿到此博客的userId，对比session中获取userId
        if(blog.getUserId() != user.getUserId()) {
            resp.setStatus(403);
            resp.getWriter().write("这不是您的博客，不可以删除");
            return;
        }
        //6.执行删除操作
        blogDao.deleteBlog(Integer.parseInt(blogId));
        //7.重定向到主页
        resp.sendRedirect("blog_list.html");
    }
}
